#!/bin/bash

NODE_NAME="/ros_webrtc"
PID_FILE="/tmp/ros_webrtc.pid"
LOG_FILE="/mnt/czx/webrtc_setup.log"

echo "[STOP] Stopping ROS WebRTC and watchdog..." | tee -a "$LOG_FILE"

# Step 1: 停 watchdog 脚本
WATCHDOG_PIDS=$(ps aux | grep '[w]ebrtc_setup.sh' | awk '{print $2}')
if [ -n "$WATCHDOG_PIDS" ]; then
    echo "[STOP] Killing watchdog script (PIDs: $WATCHDOG_PIDS)..." | tee -a "$LOG_FILE"
    kill -9 $WATCHDOG_PIDS
    echo "[STOP] Watchdog script killed." | tee -a "$LOG_FILE"
else
    echo "[STOP] No watchdog script running." | tee -a "$LOG_FILE"
fi

# Step 2: 杀掉 ROS 节点
if rosnode list 2>/dev/null | grep -q "$NODE_NAME"; then
    echo "[STOP] Killing ROS node $NODE_NAME..." | tee -a "$LOG_FILE"
    rosnode kill "$NODE_NAME" >> "$LOG_FILE" 2>&1
    echo "[STOP] ROS node killed." | tee -a "$LOG_FILE"
else
    echo "[STOP] ROS node $NODE_NAME not found." | tee -a "$LOG_FILE"
fi

# Step 3: 清除 PID 文件
if [ -f "$PID_FILE" ]; then
    echo "[STOP] Removing PID file." | tee -a "$LOG_FILE"
    rm -f "$PID_FILE"
fi

echo "[STOP] All done." | tee -a "$LOG_FILE"
